package demo7;

import java.util.LinkedList;
import java.util.Queue;

//队列实现栈
public class QueueImplementationStack {
    public Queue<Integer> queue1;
    public Queue<Integer> queue2;

    //无参构造
    public QueueImplementationStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    //入栈
    public void push(int val) {
        if (queue1.isEmpty() && queue2.isEmpty()) {
            queue1.offer(val);
        } else if (!queue1.isEmpty()) {
            queue1.offer(val);
        } else {
            queue2.offer(val);
        }
    }

    //出栈
    public int pop() {
        if (empty()) {
            throw new EmptyException("栈为空");
        }
        if (queue1.isEmpty()) {
            int size = queue2.size() - 1;
            for (int i = 0; i < size; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        } else {
            int size = queue1.size() - 1;
            for (int i = 0; i < size; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }
    }

    //获得栈顶元素
    public int peek() {
        if (empty()) {
            throw new EmptyException("栈为空");
        }
        if (queue1.isEmpty()) {
            int size = queue2.size();
            int num = 0;
            for (int i = 0; i < size; i++) {
                num = queue2.poll();
                queue1.offer(num);
            }
            return num;
        } else {
            int size = queue1.size();
            int num = 0;
            for (int i = 0; i < size; i++) {
                num = queue1.poll();
                queue2.offer(num);
            }
            return num;
        }
    }

    //判断栈是不是为空
    public boolean empty() {
        return queue2.isEmpty() && queue1.isEmpty();
    }
}
